<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Api_FriendController extends Zend_Rest_Controller
{
	public function init()
	{
		$this->_helper->viewRenderer->setNoRender(true);
	}


	public function deleteAction() {

	}

	public function getAction() {

	}

	public function headAction() {

	}

	public function indexAction() {
		try{
			$friend_mapper = new Api_Model_FriendMapper();
			$user_id = $this->_getParam('param1');

			if ($user_id != NULL){
				$friends = $friend_mapper->getAllFriends($user_id);
				$this->getresponse()->appendBody(json_encode($friends));
				$this->getResponse()->setHttpResponseCode(200);

			} else {
				throw new Exception(json_encode(array('meta' => 'Bad request')),400);
			}

		}catch(Exception $e){
			$this->getresponse()->appendBody($e->getMessage());
			$this->getResponse()->setHttpResponseCode($e->getCode());
		}
	}

	public function postAction() {
		try{
			$friend_mapper = new Api_Model_FriendMapper();
			$rawBody = $this->getRequest()->getRawBody();
			$data = Zend_Json::decode($rawBody);

			$resource = $this->_getParam('param1');
			if($resource == 'request'){
				if ($data['user_id'] != "" && $data['friend_id'] != ""){
					$friend_mapper->addFriend($data);
					throw new Exception(json_encode(array('meta' => 'OK')),200);
				} else {
					throw new Exception(json_encode(array('meta' => 'Bad request')),400);
				}
			} elseif ($resource == 'response') {
				if ($data['friend_response'] != "" && $data['user_id'] != "" && $data['friend_id'] != ""){
					$friend_mapper->confirmFriend($data);
					throw new Exception(json_encode(array('meta' => 'OK')),200);
				} else {
					throw new Exception(json_encode(array('meta' => 'Bad request')),400);
				}
			}

		}catch(Exception $e){
			$this->getresponse()->appendBody($e->getMessage());
			$this->getResponse()->setHttpResponseCode($e->getCode());
		}
	}

	public function putAction() {
		try{
			$friend_mapper = new Api_Model_FriendMapper();
			$user_id = $this->_getParam('param1');
			$friend_id = $this->_getParam('param2');
			if ($user_id != NULL && $friend_id != NULL){
				$friend_mapper->unFriend($user_id, $friend_id);
				throw new Exception(json_encode(array('meta' => 'OK')),200);

			} else {
				throw new Exception(json_encode(array('meta' => 'Bad request')),400);
			}

		}catch(Exception $e){
			$this->getresponse()->appendBody($e->getMessage());
			$this->getResponse()->setHttpResponseCode($e->getCode());
		}
	}
}
